package com.xiliu.server.modules.basicdata.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiliu.common.utils.StringUtils;
import com.xiliu.server.modules.app.vo.HouseConfigVo;
import com.xiliu.server.modules.app.vo.HouseDetailVo;
import com.xiliu.server.modules.app.vo.HouseVo;
import com.xiliu.server.modules.basicdata.entity.XlHouse;
import com.xiliu.server.modules.basicdata.entity.XlHousePic;
import com.xiliu.server.modules.basicdata.mapper.XlHouseMapper;
import com.xiliu.server.modules.basicdata.service.IXlHouseConfigService;
import com.xiliu.server.modules.basicdata.service.IXlHousePicService;
import com.xiliu.server.modules.basicdata.service.IXlHouseService;
import com.xiliu.server.modules.system.entity.XlDictData;
import com.xiliu.server.modules.system.service.IXlDictDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 房源表Service业务层处理
 * 
 * @author xiliu
 * @date 2022-11-08
 */
@Service
public class XlHouseServiceImpl extends ServiceImpl<XlHouseMapper, XlHouse> implements IXlHouseService {

    @Autowired
    private XlHouseMapper xlHouseMapper;
    @Autowired
    private IXlHousePicService housePicService;
    @Autowired
    private IXlDictDataService dictDataService;
    @Autowired
    private IXlHouseConfigService houseConfigService;

    /**
     * 查询房源表
     * @param houseId 房源表主键
     * @return 房源表
     */
    @Override
    public XlHouse selectXlHouseByHouseId(Long houseId) {
        XlHouse xlHouse = xlHouseMapper.selectXlHouseByHouseId(houseId);
        if (xlHouse != null) {
            List<XlHousePic> housePicList = housePicService.list(new LambdaQueryWrapper<XlHousePic>()
                    .eq(XlHousePic::getHouseId,houseId).orderByAsc(XlHousePic::getCreatedTime));
            if (CollectionUtil.isNotEmpty(housePicList)) {
                xlHouse.setHousePicList(housePicList);
                List<String> urlList = housePicList.stream().map(XlHousePic::getUrl).collect(Collectors.toList());
                xlHouse.setHousePics(StringUtils.join(urlList.toArray(),","));
            }
        }
        return xlHouse;
    }

    /**
     * 查询房源表列表
     * @param xlHouse 房源表
     * @return 房源表
     */
    @Override
    public List<XlHouse> selectXlHouseList(XlHouse xlHouse) {
        return xlHouseMapper.selectXlHouseList(xlHouse);
    }

    /**
     * 新增房源表
     * @param xlHouse 房源表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(XlHouse xlHouse) {
        xlHouse.setPushDate(new Date());
        xlHouse.setOrderNo(generateOrderNo());
        if (save(xlHouse)) {
            // 新增房源图片
            return saveHousePics(xlHouse.getHousePics(), xlHouse.getHouseId());
        }
        return false;
    }

    /**
     * 保存房源图片
     */
    private boolean saveHousePics(String housePics, Long houseId) {
        if (StringUtils.isNotBlank(housePics)) {
            List<XlHousePic> housePicList = new ArrayList<>();
            List<String> picStrList = Arrays.asList(housePics.split(","));
            picStrList.stream().forEach(pic -> {
                XlHousePic housePic = new XlHousePic();
                housePic.setHouseId(houseId);
                housePic.setUrl(pic);
                housePic.setName(pic.split("_")[1]);
                housePicList.add(housePic);
            });
            return housePicService.saveBatch(housePicList);
        }
        return false;
    }

    /**
     * 修改房源表
     * @param xlHouse 房源表
     * @return 结果
     */
    @Override
    public boolean update(XlHouse xlHouse) {
        if (updateById(xlHouse)) {
            // 先删除所有房源图片
            List<XlHousePic> housePicList = housePicService.list(new LambdaQueryWrapper<XlHousePic>()
                    .eq(XlHousePic::getHouseId,xlHouse.getHouseId()).orderByAsc(XlHousePic::getCreatedTime));
            housePicService.removeBatchByIds(housePicList);
            // 在新增
            return saveHousePics(xlHouse.getHousePics(), xlHouse.getHouseId());
        }
        return updateById(xlHouse);
    }

    /**
     * 批量删除房源表
     * @param houseIds 需要删除的房源表主键
     * @return 结果
     */
    @Override
    public int deleteXlHouseByHouseIds(Long[] houseIds) {
        return xlHouseMapper.deleteBatchIds(Arrays.asList(houseIds));
    }

    /**
     * 删除房源表信息
     * @param houseId 房源表主键
     * @return 结果
     */
    @Override
    public int deleteXlHouseByHouseId(Long houseId) {
        return xlHouseMapper.deleteById(houseId);
    }

    @Override
    public List<HouseVo> getHouseListByType(String type) {
        List<HouseVo> list = xlHouseMapper.getHouseListByType(type);
        if (CollectionUtil.isNotEmpty(list)) {
            for (HouseVo vo : list) {
                List<XlDictData> dictData = dictDataService.selectDictDataByType("house_highlights");
                List<String> stringList = dictData.stream().filter(item -> Arrays.asList(vo.getTags().split(",")).contains(item.getDictValue())).map(XlDictData::getDictLabel).collect(Collectors.toList());
                // 最多可显示3个标签
                if (CollectionUtil.isNotEmpty(stringList) && stringList.size() > 3) {
                    stringList = stringList.subList(0,3);
                }
                vo.setTagsName(stringList);
            }
        }
        return list;
    }

    @Override
    public HouseDetailVo getHouseDetailByHouseId(Long houseId) {
        HouseDetailVo vo = new HouseDetailVo();
        XlHouse xlHouse = xlHouseMapper.selectXlHouseByHouseId(houseId);
        if (xlHouse != null) {
            BeanUtils.copyProperties(xlHouse, vo);
            List<XlHousePic> housePicList = housePicService.list(new LambdaQueryWrapper<XlHousePic>()
                    .eq(XlHousePic::getHouseId,houseId).orderByAsc(XlHousePic::getCreatedTime));
            vo.setHousePicList(housePicList);
            vo.setTypeName(dictDataService.getDictDataLabelByType("house_type",vo.getType()));
            // 房屋亮点
            List<String> tagsName = dictDataService.getDictDataLabelsByType("house_highlights",vo.getTags());
            vo.setTagsName(tagsName);
            // 装修情况
            List<String> decorationName = dictDataService.getDictDataLabelsByType("house_decoration", vo.getDecoration());
            vo.setDecorationName(decorationName);
            // 房屋配置
            List<HouseConfigVo> configVoList = houseConfigService.getHouseConfigListByName(vo.getConfig());
            vo.setHouseConfigList(configVoList);
            vo.setStateName(dictDataService.getDictDataLabelByType("house_states",String.valueOf(vo.getState())));
            vo.setViewTime(dictDataService.getDictDataLabelByType("house_view_time",vo.getViewTime()));
            vo.setRzDate(DateUtil.format(xlHouse.getRzDate(),"yyyy-MM-dd"));
        }
        return vo;
    }

    /**
     * 随机生成房源编号八位数字随机码
     */
    private String generateOrderNo() {
        while (true) {
            StringBuilder orderNo = new StringBuilder().append(RandomUtil.randomNumbers(8));
            long count = this.count(new LambdaQueryWrapper<XlHouse>().eq(XlHouse::getOrderNo,orderNo));
            if (count == 0) {
                return orderNo.toString();
            }
        }
    }
}
